package com.mygame.gateway.server.handler.codec;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.mygame.common.utils.AESUtils;
import com.mygame.common.utils.CompressUtil;
import com.mygame.gateway.common.GatewayServerConfig;
import com.xinyue.network.message.game.GameMessageHeader;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

/**
 * 
 * @ClassName: EncodeHandler
 * @Description: 编码服务器向客户端发送的数据
 * @author: wgs
 * @date: 2019年4月7日 下午3:04:31
 */
public class EncodeHandler extends MessageToByteEncoder<GateResponseMessage> {
    private GatewayServerConfig serverConfig;
    private static Logger  logger = LoggerFactory.getLogger(EncodeHandler.class);

    public EncodeHandler(GatewayServerConfig serverConfig) {
        this.serverConfig = serverConfig;// 注入服务端配置
    }

    private String aesSecret;// 对称加密密钥

    public void setAesSecret(String aesSecret) {
        this.aesSecret = aesSecret;
    }

    @Override
    protected void encode(ChannelHandlerContext ctx, GateResponseMessage msg, ByteBuf out) throws Exception {
        try {
    	int messageSize = GameMessageHeader.HEADER_LENGTH;
        byte[] body = msg.getResponseBody();
        int compress = 0;
        
        if (body != null) {// 达到压缩条件，进行压缩
            if (body.length >= serverConfig.getCompressMessageSize()) {
                body = CompressUtil.compress(body);
                compress = 1;
            }
            if (this.aesSecret != null && msg.getHeader().getMessageId() != 1) {
               //  body = AESUtils.encode(aesSecret, body);
            }
            messageSize += 1;//添加压缩标记所点字节长度
            messageSize += body.length;
        }
        messageSize += 4;//记录消息总长度所占字节长度
        out.writeInt(messageSize);
        GameMessageHeader header = msg.getHeader();
        header.writeResponseHeader(out);
        if (body != null) {
            out.writeByte(compress);
            out.writeBytes(body);
        }
        }catch (Exception e) {
        	logger.error("网关编码消息失败",e);
        }
    }
}
